/*
 * Main.java
 *
 * Created on 24-Feb-2013, 1:29:05 PM
 */
package main;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.prefs.BackingStoreException;
import java.util.prefs.InvalidPreferencesFormatException;
import java.util.prefs.Preferences;
import ngram_converter.ConverterWindow;
import ngram_reader.validator.ValidatorWindow;
import ngram_reader.viewer.NGramSearchWindow;
import swingExtended.SwingExtended;
import variable.lazy.Lazy;
import variable.lazy.LazyValue;

/**
 *
 * @author Shimu
 */
public class Main extends javax.swing.JFrame {

    public static final String USER_PREF_ROOT_NODE = "ngram";
    private static final String USER_PREF_URL = "data/settings.xml";

    /** Creates new form Main */
    public Main() {
        initComponents();
        this.setLocationRelativeTo(null);

        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                // Save the preferences on windowClosing
                // note handling this on windowClosing instead of windowClosed
                // so we can still display warning windows if any errors occur
                Preferences pref = Preferences.userRoot().node(USER_PREF_ROOT_NODE);

                try (BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(USER_PREF_URL))) {
                    pref.exportSubtree(writer);
                    System.out.println("Successfully saved settings");

                } catch (IOException | BackingStoreException ex) {
                    SwingExtended.openWarningWindow(Main.this, "Failed to save settings file", ex);
                }
            }
        });

    }
    
    private final Lazy<NGramSearchWindow> searchWindow = 
            new LazyValue<NGramSearchWindow>() {

        @Override
        public NGramSearchWindow initialize() {
            return new NGramSearchWindow();
        }
    };
    
    private final Lazy<ConverterWindow> converterWindow = 
            new LazyValue<ConverterWindow>() {

        @Override
        public ConverterWindow initialize() {
            return new ConverterWindow();
        }
    };
    
    private final Lazy<ValidatorWindow> validatorWindow = 
            new LazyValue<ValidatorWindow>() {

        @Override
        public ValidatorWindow initialize() {
            return new ValidatorWindow();
        }
    };
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonSearch = new javax.swing.JButton();
        labelSearchDescription = new javax.swing.JLabel();
        buttonConvert = new javax.swing.JButton();
        labelConvertDescription = new javax.swing.JLabel();
        buttonValidate = new javax.swing.JButton();
        labelValidateDesc = new javax.swing.JLabel();
        labelValidateDesc2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        buttonSearch.setText("Search");
        buttonSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSearchActionPerformed(evt);
            }
        });

        labelSearchDescription.setText("Search for an n-gram");

        buttonConvert.setText("Convert");
        buttonConvert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonConvertActionPerformed(evt);
            }
        });

        labelConvertDescription.setText("Convert from Google's original n-gram format to a format used by this program");

        buttonValidate.setText("Validate");
        buttonValidate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonValidateActionPerformed(evt);
            }
        });

        labelValidateDesc.setText("Validate the files after conversion to make sure no files are corrupted.");

        labelValidateDesc2.setText("Corrupted files must be reconverted.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonConvert)
                            .addComponent(buttonSearch))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelConvertDescription, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(labelSearchDescription)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonValidate)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelValidateDesc2)
                            .addComponent(labelValidateDesc, javax.swing.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSearch)
                    .addComponent(labelSearchDescription))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonConvert)
                    .addComponent(labelConvertDescription))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonValidate)
                    .addComponent(labelValidateDesc))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelValidateDesc2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSearchActionPerformed
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                searchWindow.getValue().setVisible(true);
            }
        });
    }//GEN-LAST:event_buttonSearchActionPerformed

    private void buttonConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConvertActionPerformed
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                converterWindow.getValue().setVisible(true);
            }
        });
    }//GEN-LAST:event_buttonConvertActionPerformed

    private void buttonValidateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonValidateActionPerformed

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                validatorWindow.getValue().setVisible(true);
            }
        });
    }//GEN-LAST:event_buttonValidateActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        try (BufferedInputStream reader = new BufferedInputStream(new FileInputStream(USER_PREF_URL))) {
            Preferences.importPreferences(reader);
            System.out.println("Successfully loaded settings");

        } catch (IOException | InvalidPreferencesFormatException ex) {
            System.out.println("Failed to load settings");
            ex.printStackTrace();
        }
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonConvert;
    private javax.swing.JButton buttonSearch;
    private javax.swing.JButton buttonValidate;
    private javax.swing.JLabel labelConvertDescription;
    private javax.swing.JLabel labelSearchDescription;
    private javax.swing.JLabel labelValidateDesc;
    private javax.swing.JLabel labelValidateDesc2;
    // End of variables declaration//GEN-END:variables
}
